<template>
  <div class="AAA" style="width: 100%;">
      <a-layout class="layout-demo">
        <a-layout-sider
            theme="light"
            :height="30"
            breakpoint="xxl"
            :width="380"
            :style="{ height: '93.2%'}"
            collapsible
            :collapsed="collapsed"
            @collapse="onCollapse"
        >
          <a-menu
              style="margin-button: 50px"
              :defaultOpenKeys="['0']"
              :defaultSelectedKeys="['0']"
          >
            <a-sub-menu key="0">
              <template #title>
                <span><el-icon><UserFilled /></el-icon>沟通过<span style="margin-left:200px">{{userArr.length>0?userArr.length:0}}人</span></span>
              </template>
              <a-menu-item v-for="(item,index) in userArr" :key="item.username"
                           v-show="index>=0"
                           @click="checkUser(item)"
                           :class="{'user-name-check':item.status=='在线'}">
                <span>
                  <el-avatar v-if="BASE_URL+item.userImg.length!=null" fit="cover" :src="BASE_URL+item.userImg" style="margin-top: 15px"/>
                  <el-avatar v-else
                             style="margin-top: 15px"
                             src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                  />
                   <div style="margin-left:10px;margin-top: 20px;display: inline;">{{item.name}}</div>
                </span>
                <div style="display: inline;">
<!--                  在线状态-->
                <span style="float: right">
                  <div v-if="item.status=='在线'" style="margin-top: 30px">
                   <div class="circle">
            <div class="big-circle"></div>
            <div class="small-circle"></div>
        </div>
                </div>
                  <div v-else style="margin-top: 30px">
                 <div class="circle2">
            <div class="big-circle2"></div>
            <div class="small-circle2"></div>
        </div>
                  </div>
                </span>
                </div>
              </a-menu-item>

            </a-sub-menu>
          </a-menu>
        </a-layout-sider>
<!--        对话框-->
        <a-layout style="height: 100%">
          <a-layout-header>
           <h3 style="color: #4c2a70;margin-left: 20px">对话框</h3>
          </a-layout-header>
              <div class="chat-right">
                <a-scrollbar style="height:478px;overflow: auto;">
                  <div style="min-height:478px;width: 100%; background-color: rgba(145,103,252,0.49)">
                    <div  ref="smgContent">
                      <div  v-for="item in msgArr" :key="item">
                        <el-row>
                          <div v-if="item.split('::++')[0]==username">
                            <div  class="RItemMsg">{{item.split('::++')[1]}}</div>
                          </div>
                          <div v-else>
                            <div  class="LItemMsg">{{item.split('::++')[1]}}</div>
                          </div>
                        </el-row>
                      </div>
                    </div>
                  </div>
                </a-scrollbar>
                <div class="input-box">
                  <el-input
                      v-model="textarea"
                      @keydown.enter="keydown"
                      placeholder="说点什么吧~"
                      :autosize="{ minRows: 7, maxRows: 7 }"
                      type="textarea"/>
                  <a-button type="primary" size="large"  @click="sendBtn" class="btn">发送</a-button>
                </div>
              </div>
        </a-layout>
      </a-layout>
  </div>
</template>
<script>
import { defineComponent, ref } from 'vue';
import {
  IconHome,
  IconCalendar,
} from '@arco-design/web-vue/es/icon';

export default defineComponent({
  components: {
    IconHome,
    IconCalendar,
  },
  setup() {
    const collapsed = ref(false);
    const onCollapse = (val) => {
      collapsed.value = val;
    }
    return {
      collapsed,
      onCollapse,
    };
  }
});
</script>
<script setup>
//Todo
//需要加的数据：招聘名称，薪资，地点，在聊天时显示头像、对话框
import {ref, defineExpose, nextTick, onMounted} from 'vue'
import axios from 'axios'
import qs from "qs";
import {ElMessage} from "element-plus";

const dialogVisible = ref(true)
const smgContent = ref()
const textarea = ref('')
let chatWS = null
const user = ref(getUser());
const username= user.value.username;
console.log(username);
let toUser = {id:null,name:null} // 要发送人的ID
const userArr = ref([]) // 人员数组
const activeNames = ref(['0'])
const msgArr = ref([])
// connectWebSocket()
onMounted(() => {
  connectWebSocket()
  obtainName() // 调取人员接口
})
function connectWebSocket () {
  console.log('connectWebSocket');
  // 判断当前浏览器是否支持WebSocket
  dialogVisible.value = true
  if ('WebSocket' in window) {
    // chatWS = new WebSocket('ws://172.16.26.37:8081/websocket/' + username)0
    console.log(username)
    console.log(username.value)
    // let socketUrl = "ws://localhost:8080/websocket/" + username;
    chatWS = new WebSocket('ws://localhost:8080/websocket/'+username)

  } else {
    alert('当前浏览器不支持Websocket')
  }
  chatWS.onmessage = (evt) => {
    console.log(evt.data,'人员更新');
    if (evt.data==='人员更新') {
      obtainName() // 调取人员接口
    }else{
      msgArr.value.push(evt.data)
    }
    // nextTick(()=>{
    //   smgContent.value.scrollTop = smgContent.value.scrollHeight
    // })
  }
}

// 获取聊天人员接口
function obtainName () {
  // axios.get('http://172.16.26.37:8002/java_backend/members').then(res => {
  axios.post('http://localhost:8080/v1/chat/members/'+username).then(res => {
    userArr.value = res.data.data.map(item => {
          item.isCheck = false
          if (toUser.id === item.username) {
            item.isCheck = true
          }
          return item
        },
        console.log(userArr.value)
    )
  })
}

// 选择群聊或者单聊  获取聊天记录
function checkUser (item) {
  console.log("wwwwwwww"+item.username);
  msgArr.value = [] // 清空聊天框内容
  userArr.value.forEach(i => {
    if (i.username !== item.username) {
      i.isCheck = false
    }
  })
  // 保存 选择人员的ID和name 并通过id 来区分是群聊还是单聊
  item.isCheck = !item.isCheck
  toUser.username = item.username
  console.log("66666"+toUser.name)
  if (item.isCheck) {
    toUser.id = item.username
    console.log("1111111"+toUser.id);
    console.log("222222"+item.username)
  } else {
    toUser.id = ''
  }
  let data = qs.stringify({
    type: toUser.id === '' ? 0 : 1,
    toUser:toUser.id,
    fromUser:username
  });
  console.log('获取聊天记录');
  console.log(data);

  // 获取聊天记录
  axios.post('http://localhost:8080/v1/chat/message',data).then(res => {
    let type =toUser.id === '' ? true : false
    if (type) {
      res.data.data.forEach(item=>{
        msgArr.value.push(`${item.fromName}：${item.message}`) // 群聊
      })
    }else{
      if (Array.isArray(res.data.data)) {
        res.data.data.forEach(item => {
          console.log(`${item.fromName}->${item.toName}：${item.message}`);//打印
          msgArr.value.push(`${item.fromName}::++${item.message}`); // 单聊
        });
      } else {
        console.error('数据不是数组:', res.data.data);
      }
    }
    // nextTick(()=>{
    //   smgContent.value.scrollTop = smgContent.value.scrollHeight
    // })
  })
}
// 发送消息
function keydown(e) {
  if (e.ctrlKey && e.keyCode === 13) {
    // 换行
    textarea.value = textarea.value + '\n'
  }
  if (e.ctrlKey === false && e.keyCode === 13) {
    // 阻止浏览器默认行为  禁止发送时输入框换行
    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
    // 发送
    sendBtn()
  }
}

function sendBtn () {
  if (!toUser.id){
    ElMessage.error("请先选择对象")
    return
  }
  if (textarea.value !== '') {
    const socketMsg = {msg: textarea.value,toUser:toUser.id,type: toUser.id === '' ? 0 : 1}
    chatWS.send(JSON.stringify(socketMsg))
    textarea.value = ''
  }
}
// 关闭连接
function closeWebSocket () {
  chatWS.close()
  userArr.value = []
  textarea.value = ''
  msgArr.value = []
  dialogVisible.value = false
}
// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
  chatWS.close()
}
defineExpose({
  connectWebSocket
})
</script>

<style scoped>
*{
  padding: 0;
  margin: 0;
}
.AAA{
  width: 100%;
  height: 100%;
  min-height: 94vh;
  background-size: 100% 100%;
  background: linear-gradient(-135deg, #4f03ab, #8661f5, #fcfcfc);
  background-size: 200% 200%;
  animation: moveAnimation 4s infinite;
  max-height: 180vh;
  overflow: auto;
}
@keyframes moveAnimation {
  0% {
    background-position: 0% 50%
  }
  50% {
    background-position: 100% 70%
  }
  100% {
    background-position: 0% 50%
  }
}
.layout-demo {
  width: 80%;
  height: 700px;
  margin: 0 auto;
  margin-top:40px;
  background: var(--color-fill-2);
  border: 1px solid var(--color-border);
}
.layout-demo :deep(.arco-layout-header)  {
  height: 64px;
  line-height: 64px;
  background: var(--color-bg-3);
}
.layout-demo :deep(.arco-layout-footer) {
  height: 48px;
  color: var(--color-text-2);
  font-weight: 400;
  font-size: 14px;
  line-height: 48px;
}
.layout-demo :deep(.arco-layout-content) {
  color: var(--color-text-2);
  font-weight: 400;
  font-size: 14px;
  background: var(--color-bg-3);
}
.layout-demo :deep(.arco-layout-footer),
.layout-demo :deep(.arco-layout-content)  {
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: var(--color-white);
  font-size: 16px;
  font-stretch: condensed;
  text-align: center;
}

@keyframes twinkling {
  0% {
    opacity: 0.2;
    transform: scale(1);
  }

  50% {
    opacity: 0.5;
    transform: scale(1.12);
  }

  100% {
    opacity: 0.2;
    transform: scale(1);
  }
}


.circle {
  position: relative;
  width: 24px;
  height: 24px;
}

.small-circle {
  border-radius: 50%;
  width: 12px;
  height: 12px;
  background: #258505;
  position: absolute;
}

.big-circle {
  position: absolute;
  top: -6px;
  left: -6px;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(53, 203, 19, 0.74);
  animation: twinkling 1s infinite ease-in-out;
  animation-fill-mode: both;
}

@keyframes scale {
  0% {
    transform: scale(1)
  }

  50%,
  75% {
    transform: scale(3)
  }

  78%,
  100% {
    opacity: 0
  }
}

@keyframes scales {
  0% {
    transform: scale(1)
  }

  50%,
  75% {
    transform: scale(2)
  }

  78%,
  100% {
    opacity: 0
  }
}

.circle2 {
  position: relative;
  width: 24px;
  height: 24px;
}

.small-circle2 {
  border-radius: 50%;
  width: 12px;
  height: 12px;
  background: #525252;
  position: absolute;
}

.big-circle2 {
  position: absolute;
  top: -6px;
  left: -6px;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(49, 49, 49, 0.74);
  animation: twinkling 1s infinite ease-in-out;
  animation-fill-mode: both;
}

@keyframes scaless {
  0% {
    transform: scale(1)
  }

  50%,
  75% {
    transform: scale(3)
  }

  78%,
  100% {
    opacity: 0
  }
}

.btn{
  position: absolute;
  right: 180px;
  width: 50px;
  margin-top: 120px;
}
.RItemMsg{
  float: right;
  max-width: 450px;
  word-wrap:break-word;
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
}
.LItemMsg{
  float: left;
  max-width: 450px;
  word-wrap:break-word;
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
}
</style>
